package com.wang.book.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.book.entity.Book;
import com.wang.book.exception.BusinessException;
import com.wang.book.mapper.BookMapper;
import com.wang.book.mapper.BookTypeMapper;
import com.wang.book.service.BookService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@RequiredArgsConstructor
public class BookServiceImpl implements BookService {
    @Autowired
    private  BookMapper bookMapper;
    @Autowired
    private final BookTypeMapper bookTypeMapper;

    @Transactional
    public Boolean addBook(Book book) {
        if (bookTypeMapper.countBooksByType(book.getTypeNo())==0) {
            throw new BusinessException("指定分类不存在");
        }
        //插入成功
        if (bookMapper.insert(book)>0){
            return true;
        }
        return false;
    }

    public Page<Book> listBooks(int page, int size) {
        return bookMapper.selectPage(new Page<>(page, size), null);
    }

    @Override
    public boolean deleteBook(Integer id) {
        //删除成功
        if (bookMapper.deleteById(id)>0){
            return true;
        }
        return false;
    }

    @Override
    public Book getBookById(int id) {
    return bookMapper.selectById(id);
    }

    @Override
    public Book updateBook(Book book) {
        if (bookMapper.updateById(book)>0){
            return bookMapper.selectById(book.getNo());
        }
        return null;
    }
}
